<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                  <el-form-item label="类型" prop="type">
                    <el-tree-select
                        v-model="queryParams.type"
                        :data="categoryList"
                        :render-after-expand="false"
                        :props="{ label: 'name',value:'id' }"
                        style="width: 240px"
                      />
                     <!-- <el-select v-model="queryParams.type" placeholder="请选择类型" clearable filterable style="width: 200px">
                        <el-option
                            v-for="item in categoryList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                      </el-select> -->
                  </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['stamp:index:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
      
      <!-- <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['stamp:index:remove']"
        >删除</el-button>
      </el-col> -->
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stampList" @selection-change="handleSelectionChange">
              <el-table-column label="id" align="center" prop="id" />
              <el-table-column label="标题" align="center" prop="memo" >
                 <template #default="scope">
                  <!-- 小于12位默认展示 -->
                  <div v-if="scope.row.memo != null && scope.row.memo.length <= 10">
                    {{ scope.row.memo }}
                  </div>
                  <!-- 大于12为只展示12位 -->
                  <el-tooltip
                    v-if="scope.row.memo != null && scope.row.memo.length > 10"
                    popper-class="testtooltip"
                    :content="scope.row.memo"
                    placement="top-start"
                  >
                    <div>{{ scope.row.memo.slice(0, 10) }}...</div>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column label="图片" align="center" prop="images" >
                <template #default="scope">
                  <image-preview :src="scope.row.images" :width="50" :height="50" />
                </template>
              </el-table-column>
              <el-table-column label="类型" align="center" prop="typeName" />
              <el-table-column label="排序" align="center" prop="sort" />
              <el-table-column label="创建名称" align="center" prop="createName" />  
              <el-table-column label="创建时间" align="center" prop="createTime" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['stamp:index:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['stamp:index:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改图库对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="stampRef" :model="form" :rules="rules" label-width="80px">
           <el-form-item label="标题" prop="memo">
            <el-input v-model="form.memo" placeholder="请输入标题" />
          </el-form-item>
        <el-form-item label="类型" prop="type">
                    <el-tree-select
                      v-model="form.type"
                      :data="categoryList"
                      :render-after-expand="false"
                      :props="{ 
                        label: 'name',
                        value: 'id',
                        isLeaf: 'isLeaf' // 假定支持判断是否叶子节点的属性
                      }"
                      @change="handleTypeChange"
                      style="width: 240px"
                    />
        </el-form-item>
          <el-form-item label="图片" prop="images">
             <image-upload v-model="form.images" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="form.sort"  :min="1" />
          </el-form-item>
       
     
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Stamp">

  import { listStamp, getStamp, delStamp, addStamp, updateStamp } from "@/api/main/stamp";
  import { listCategory } from "@/api/main/category";

  const { proxy } = getCurrentInstance();

  const stampList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const categoryList = ref([]);
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      images: null,
      type: null,
      sort: null,
      memo: null,
      status: null,
      createUser: null,
      createName: null,
      updateUser: null,
      updateName: null,
      typeName: null
    },
    rules: {
      type: [{ required: true, message: "类型不能为空", trigger: "change" }],
      memo: [{ required: true, message: "标题不能为空", trigger: "change" }],
      images: [{ required: true, message: "图片不能为空", trigger: "change" }]
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询图库列表 */
  function getList() {
    loading.value = true;
    listStamp(queryParams.value).then(response => {
            stampList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }
  //查看类型列表
  function getCategoryList(){
    listCategory({type:0}).then(res=>{
      categoryList.value = res.data.filter(temp => temp.children != null && temp.children.length > 0);
    })
  }
  function handleTypeChange(data){
    // console.log(data)
    // // 假设node参数代表了被选择的节点对象
    // const type = categoryList.value.filter((parent) => {
    // // 检查每个父节点的children数组中是否有元素的id等于data
    // // 如果有，some()方法会返回true，并且该父节点会被包含在最终的结果中
    //     return parent.pid;
    // });
    // console.log(type[0].children)
    // const filteredParents = type[0].children.filter(parent => 
    //  console.log(parent)
    //     // parent.id==data
    // );
    
    // if (filteredParents[0].pid==0) {
    //   form.value.type=null;
    //   return proxy.$modal.msgError('只能选择子级选项，请重新选择。');
    //   // 重置所选项，这里的实现依赖于你的具体数据结构和组件
    //   // this.form.type = null 或者采取其他适当的重置操作
    // } else {
    //   // 是叶子节点，正常处理选择逻辑
    //   // 更新form.type或其他必要的数据操作
    //     if (type.length>0) {
    //         form.value.typeName = filteredParents[0].name;
    //       } else {
    //         form.value.typeName = null;
    //       }
    // }
   
  }
  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

  // 表单重置
  function reset() {
    form.value = {
                    id: null,
                    images: null,
                    type: null,
                    sort: null,
                    memo: null,
                    status: null,
                    delFlag: null,
                    createUser: null,
                    createName: null,
                    createTime: null,
                    updateUser: null,
                    updateName: null,
                    updateTime: null,
                    typeName: null
    };
    proxy.resetForm("stampRef");
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加图库";
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value
    getStamp(_id).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改图库";
    });
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["stampRef"].validate(valid => {
      if (valid) {
        if (form.value.id != null) {
          updateStamp(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addStamp(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除图库编号为"' + _ids + '"的数据项？').then(function() {
      return delStamp(_ids);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('system/stamp/export', {
      ...queryParams.value
    }, `stamp_${new Date().getTime()}.xlsx`)
  }

  getList();
  getCategoryList();
</script>
